﻿using System.Collections.Concurrent;

namespace DesignModeConsole.创建型.工厂方法模式;

/// <summary>
/// 工厂方法
/// </summary>
public class FactoryMethodService : IService
{
    /// <summary>
    /// 工厂方法
    /// 使用场景：适合创建对象的方法比较复杂，或者需要进行其他扩展
    /// </summary>
    public void Main()
    {
        var parser = ReadFileParserFactoryMap.GetParserFactory("json");
        if (parser == null)
            throw new ArgumentException("无效的读取规则");

        //读取文件的类
        var readFile = parser.CreateParser();
        Console.WriteLine(readFile.Read());
    }
}

/// <summary>
/// 文件读取工厂
/// </summary>
public static class ReadFileParserFactoryMap
{
    private static readonly ConcurrentDictionary<string, IReadFileParserFactory> _files = new ConcurrentDictionary<string, IReadFileParserFactory>();

    static ReadFileParserFactoryMap()
    {
        _files.TryAdd("json", new ReadJsonFileParserFactory());
        _files.TryAdd("xml", new ReadXmlFileParserFactory());
        _files.TryAdd("txt", new ReadTxtFileParserFactory());
    }

    public static IReadFileParserFactory? GetParserFactory(string fileFormat)
    {
        _files.TryGetValue(fileFormat, out var result);
        return result;
    }
}